import { Form } from '@ant-design/compatible';
import { DownOutlined, PlusOutlined,InfoCircleOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Col, Checkbox,message,Tooltip} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';
import DataLang from './DataLang';


// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}
const { Option } = Select;
// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate, dataFormValues } = props;

  const parseData = (key:any,options:any) => {
    // console.log(options);
    var name:any = "";
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          name = item?.item_value;
        }
      })
    }
    return name
  }

  const parseDataItem = (key:any,options:any) => {
    var obj:any = {};
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          obj = item;
        }
      })
    }
    return obj
  }

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureLogo, setPictureLogo] = useState<any[]>([]);
  const [uploadLogoChanged, setUploadLogoChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [account_terms_close,setaccount_terms_close] = useState<boolean>(parseData('account_terms_close',dataFormValues) || false);
  const [account_privacy_close,setaccount_privacy_close] = useState<boolean>(parseData('account_privacy_close',dataFormValues) || false);
  const [account_cookie_close,setaccount_cookie_close] = useState<boolean>(parseData('account_cookie_close',dataFormValues) || false);
  const [account_delete_close, setAccount_delete_close] = useState<boolean>(parseData('account_cookie_close',dataFormValues) || false);

  const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [fieldTitle, setFieldTitle] = useState<any>('');
  const [accountTermsJson, setAccountTermsJson] = useState<any>(parseDataItem('account_terms',dataFormValues).lang_json_arr || []);
  const [accountPrivacyJson, setAccountPrivacyJson] = useState<any>(parseDataItem('account_privacy',dataFormValues).lang_json_arr || []);
  const [accountCookieJson, setAccountCookieJson] = useState<any>(parseDataItem('account_cookie',dataFormValues).lang_json_arr || []);
  const [accountDeleteJson, setAccountDeleteJson] = useState<any>(parseDataItem('account_delete',dataFormValues).lang_json_arr || []);


  const [nameListLang, setnameList] = useState<any>(common?.languagesOption);
  

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log(fieldsValue.register_login_flow);
      console.log("submit fields ", fieldsValue)
      //请求当前一组配置参数，tag=accounts
      var submitValue = [
          {
            alias_key: 'accounts',
            item_type:'system',
            dict_item_arr: [
              {
                alias_key: "delete_account",
                item_value: fieldsValue.delete_account,
                item_type:"radio",
              },
              {
                alias_key: "delete_account_todo",
                item_value: (fieldsValue.delete_account == '3' || fieldsValue.delete_account == '2') ? fieldsValue.delete_account_todo : null,
                item_type:"number",
              },
            ]
          }
      ]
      // 如果更新成功之后，重置表单
      updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
        console.log('handleSubmit then success is ', JSON.stringify(submitValue))
        if(res.code == 0){
          message.success('保存成功')
          // form.resetFields()
          // setPicture([]);
          // setPictureLogo([]);
        }
      })

    });
  };

      // 表单提交
      const handleSubmitDataForm = (value:any,title:any) => {
        console.log(value,241)
        setnameList(value)
        if(title == "account_terms"){
          setAccountTermsJson(value);
        }else if(title == "account_privacy"){
          setAccountPrivacyJson(value);
        }else if(title == "account_cookie"){
          setAccountCookieJson(value);
        }else if(title == "account_delete"){
          setAccountDeleteJson(value);
        }
        handleDataModalVisible(false)
      }

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置Logo上传文件值
    const setLogoUploadFile = (fileList:any) => {
      setUploadLogoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureLogo(fileArr)
        setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureLogo([])
      }
    }

  

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.site_icon)
  const defaultLogoPicture = DataHelper.buildFileByUrl(dataFormValues.site_logo)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadLogoButton = DataHelper.showUploadBtn(isUpdate, pictureLogo, defaultLogoPicture, uploadLogoChanged)

  const plainOptions = ['电子邮箱', '手机号'];
  const otherOptions = ['微信快捷登录', 'QQ 快捷登录','微博快捷登录','字节跳动快捷登录','Google 快捷登录', 'Facebook 快捷登录', 'Twitter 快捷登录','Apple 快捷登录','Github 快捷登录'];

  // 弹出框
  // @ts-ignore
  return <Card>
             
    <Col span={24}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
      label={
        <span>
          <FormattedMessage id="Cancellation of setting" />
          <em className={styles.optional}>
            <Tooltip title={<FormattedMessage id="软注销只是将账号标注为注销，但保留账号的所有数据;硬注销将从数据库中删除账号的所有信息" />}>
              <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
            </Tooltip>
          </em>
        </span>
      }>
        {form.getFieldDecorator('delete_account', {
          initialValue: parseData('delete_account',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Radio.Group buttonStyle="solid">
        <Radio value={'1'}>不启用注销功能</Radio>
        <Radio value={'2'}>软注销</Radio>
        <Radio value={'3'}>硬注销</Radio>
      </Radio.Group>)}
      </FormItem>
    </Col>
    {
      (form.getFieldValue('delete_account') == '3' || form.getFieldValue('delete_account') == '2') && 
          <Col span={24}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({id: 'Hard write-off buffer period'})} style={{marginBottom: 15}} extra="用户在缓冲期天数内可以撤销注销（恢复账号），到期未撤销将执行注销流程。">
              {form.getFieldDecorator('delete_account_todo', {
                initialValue: (form.getFieldValue('delete_account') == '3' || form.getFieldValue('delete_account') == '2') ? parseData('delete_account_todo',dataFormValues) : null,
                rules: [{ pattern: /^[0-9]*$/, message: '请输入合理的天数' }],
              })(<Input addonAfter="天" placeholder="" style={{width:'100%'}} />)}
            </FormItem>
          </Col>
    }
    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okHandle()}}>提交保存</Button>
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
    <DataLang
        dataModalVisible={dataLangModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={common || {}}
        nameList={nameListLang}
        title={fieldTitle}
        onSubmit={handleSubmitDataForm}
        onCancel={() => handleDataModalVisible(false)}
    />
  </Card>;
};

export default Form.create<DataFormProps>()(DataForm);
